﻿using AppDataStruct;
using ComLib.ComType;
using ComUIControl;
using KWindow.KPageCore;
using LogLib;
using Newtonsoft.Json;
using System;
using System.Diagnostics;

namespace IPCPages
{
    public class ProcessReadIDCard : PageProcessBase<ProcessReadIDCard>
    {       
        private DeviceControl _device = null;
      
        public IDCardAll IDCardInfo { get; set; } = new IDCardAll();

        private ProcessReadIDCard() : base()
        {
        }

        public override void Init()
        {
            base.Init();
        }

        public override void Exit()
        {
            base.Exit();
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            _device = new DeviceControl("IDCardReader");
            _device.OnCatchException = OnCatchException;
            _device.OnWorkingDone = OnReadSuccess;
            _device.OnWorkingFailed = OnReadFailed;
            _device.OnTimeout = OnReadTimeout;
            if (!_device.Init())
            {
                MsgBox.Show($"设备管理器初始化失败:{_device.Error}");
            }
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            if (_device != null)
            {
                _device.Dispose();
                _device = null;
            }
            IDCardInfo = null;
        }

        public override void StartWork()
        {
            base.StartWork();
            if (_device != null)
            {
                _device.Start();
            }
        }

        public override void StopWork()
        {
            base.StopWork();
            if (_device != null)
            {
                _device.Stop();
            }
        }

        public override void PlayWelcomeVoice()
        {
            base.PlayWelcomeVoice();
        }

        private void OnReadSuccess(string outParams)
        {   
            string msg = $"读取结果: \n{outParams}";
            Log.WriteAsync(msg);
            try
            {
                // 在这里处理身份证信息解析结果
                IDCardInfo = JsonConvert.DeserializeObject<IDCardAll>(outParams);
                Action handler = () =>
                {
                    UpdateData();
                    //ToAny("IPCPages.PageNeedAttention");
                    ToNext();
                };
                MainPage.Invoke(handler);
            }
            catch (Exception ex)
            {
                Log.WriteExceptionAsync(ex.ToString());
                MsgBox.Show($"解析读取身份证信息结果发生了异常:\n{ex.Message}");
            }
        }

        private void OnReadFailed(string outParams, string error)
        {
            string msg = string.Format("身份证信息读取错误: \n{0}", error);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MsgBox.Show(e);
                ToHome();
            };
            for (int i = 0; i < Pages.Count; i++)
            {
                Pages[i].Invoke(handler, msg);
            }            
        }

        private void OnReadTimeout(string outParams)
        {
            string msg = string.Format("读取身份证信息超时: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MsgBox.Show(e);
                StopWork();
                ToHome();
            };
            for (int i = 0; i < Pages.Count; i++)
            {
                Pages[i].Invoke(handler, msg);
            }           
        }

        private void OnCatchException(string outParams)
        {
            string msg = string.Format("设备运行发生了异常: \n{0}", outParams);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                MsgBox.Show(e);
                StopWork();
                ToHome();
            };
            MainPage?.Invoke(handler, msg);
        }

        /// <summary>
        /// 保存身份证信息，用于预受理
        /// </summary>
        private void SetSFZData()
        {
            SFZInfo info = new SFZInfo();
            info.Address = IDCardInfo.address;
            info.BirthDate = IDCardInfo.birthday;
            info.ExpiryDate = IDCardInfo.validtermOfStart + "-" + IDCardInfo.validtermOfEnd;
            info.HeaderPicturePath = IDCardInfo.HeadImage;
            info.IsManualInputNumberVerify = IDCardInfo.IsManualInputNumberVerify;
            info.IssueUnit = IDCardInfo.signdate;
            info.Name = IDCardInfo.name;
            info.Nation = IDCardInfo.people;
            info.Sex = IDCardInfo.sex;
            info.SFZH = IDCardInfo.number;
            info.ExpiryStartDate = IDCardInfo.validtermOfStart; ;
            info.ExpiryEndDate = IDCardInfo.validtermOfEnd;
            
            SetValue("SFZInfo", info);
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            if(IDCardInfo == null)
            {
                Log.WriteAsync("获取身份证信息失败.");
                MsgBox.Show("获取身份证信息失败.");
                return;
            }
            if(MainPage != null)
            {
                if (MainPage.UserAction == UserApplyAction.TakePhotoAndWeiYinTB
                || MainPage.UserAction == UserApplyAction.TakePhotoAndYSL
                || MainPage.UserAction == UserApplyAction.OnlyYSL)
                {
                    SetSFZData();
                }
                
                string personDir = _config.OutputDirs[IDCardInfo.number];
                SetValue("PersonDataDirectory", personDir);
            }

            SetValue("IDCardInfo", IDCardInfo);
        }
    }
}
